package com.sitech.openapi.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sitech.openapi.dto.ProdPreOrder;
import com.sitech.openapi.dto.ProdPreOrderExample;
import com.sitech.openapi.dto.ProdPreOrderHis;
import com.sitech.openapi.mapper.ProdPreOrderHisMapper;
import com.sitech.openapi.mapper.ProdPreOrderMapper;
import com.sitech.openapi.mapper.ProdPreOrderMapperService;
import com.sitech.openapi.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by zhangsq on 2018/12/5.
 * 关于随选宽带甩单集约销售支撑工作的通知需求
 * 新增订单状态通知 OrderNotification,根据通知类型及状态区分
 * 预受理订单信息发布；
 * 订单竣工通知；
 * 宽带资源确认通知：
 */
@Service
@Slf4j
public class ProdPreOrderServiceImpl implements ProdPreOrderService {

    @Autowired
    private ProdPreOrderMapperService prodPreOrderMapperServcie;
    @Autowired
    private ProdPreOrderMapper prodPreOrderMapper;
    @Autowired
    private ProdPreOrderHisMapper prodPreOrderHisMapper;
    @Autowired
    private ObjectMapper mapper;

    @Override
    public Map doOrderNotificationJson(Map inMap) throws Exception {
        log.info("#######################进入服务doOrderNotificationJson");
        try {
            String inParamBodys = StringUtil.obj2Str(inMap.get("inParamBodys"));
            inMap = mapper.readValue(inParamBodys, Map.class);
            String notificationId = StringUtil.obj2Str((inMap.get("notificationId")));
            String notifyTime = StringUtil.obj2Str(inMap.get("notifyTime"));
            String custOrderId = StringUtil.obj2Str(inMap.get("custOrderId"));
            String extCustOrderId = StringUtil.obj2Str(inMap.get("extCustOrderId"));
            String reasonDesc = StringUtil.obj2Str(inMap.get("reasonDesc"));
            String reasonCode = StringUtil.obj2Str(inMap.get("reasonCode"));
            Date currentDate = prodPreOrderMapperServcie.queryCurrentDate();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
            String dateString = formatter.format(currentDate);
            /* notifyType 通知类型
            1000 订单信息发布
            1100 订单支付通知
            1200 订单提交通知（通知外围订单正式生成）
            1300 订单竣工通知
            1400 预受理订单信息发布
            */
            String notifyType = StringUtil.obj2Str(inMap.get("notifyType"));
            /**
             * notifyStatusCd 订单状态
             * 100002	保存已通过校验，已提交之后
             * 300000	竣工
             * 400000	竣工异常
             * 401300	已退单
             * 401700    已撤单
             */
            String notifyStatusCd = StringUtil.obj2Str(inMap.get("statusCd"));
            if ("1400".equals(notifyType)) {
                Map prodPreOrderJson = (Map) inMap.get("prodPreOrder");

                Map customerOrderItem = (Map) prodPreOrderJson.get("customerOrderItem");
                Map ordCustomer = (Map) customerOrderItem.get("ordCustomer");
                String custId = StringUtil.obj2Str(ordCustomer.get("custId"));
                String custName = StringUtil.obj2Str(ordCustomer.get("custName"));
                String createStaff = StringUtil.obj2Str(prodPreOrderJson.get("createStaff"));
                /**operType
                 * 1000	新建
                 * 1100	变更
                 * 1200	撤单
                 * 1300作废
                 */
                String operType = StringUtil.obj2Str(prodPreOrderJson.get("operType"));
                String remark = StringUtil.obj2Str(prodPreOrderJson.get("remark"));
                String statusCd = StringUtil.obj2Str(prodPreOrderJson.get("statusCd"));
                String sysSource = StringUtil.obj2Str(prodPreOrderJson.get("sysSource"));
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
                String acceptDates = StringUtil.obj2Str(prodPreOrderJson.get("acceptDate"));
                Date acceptDate = dateFormat.parse(acceptDates);
                String acceptRegionId = StringUtil.obj2Str(prodPreOrderJson.get("acceptRegionId"));
                acceptRegionId = acceptRegionId.substring(1, 5);
                List mainOfferOrderItems = (List) prodPreOrderJson.get("mainOfferOrderItems");

                for (int i = 0; i < mainOfferOrderItems.size(); i++) {
                    Map mainOfferOrderJson = (Map) mainOfferOrderItems.get(i);
                    List accessProdOrderItems = (List) mainOfferOrderJson.get("accessProdOrderItems");
                    String offerNbr = StringUtil.obj2Str(mainOfferOrderJson.get("offerNbr"));
                    for (int j = 0; j < accessProdOrderItems.size(); j++) {
                        Map accessProdOrderJson = (Map) accessProdOrderItems.get(j);
                        String accNbr = StringUtil.obj2Str(accessProdOrderJson.get("accNum"));
                        String prodNbr = StringUtil.obj2Str(accessProdOrderJson.get("prodNbr"));
                        String paymentModeCd = StringUtil.obj2Str(accessProdOrderJson.get("paymentModeCd"));
                        String accNbrTypeCd = "";
                        Map paraMap = new HashMap();
                        paraMap.put("offerNbr", offerNbr);
                        paraMap.put("productNbr", prodNbr);
                        paraMap.put("paymentModeCd", paymentModeCd);
                        List offerInfoList = prodPreOrderMapperServcie.queryOfferInfoById(paraMap);
                /*        if (offerInfoList == null || offerInfoList.size() == 0) {
                            throw new Exception("根据销售品" + offerNbr + "编码产品编码" + prodNbr + "找不到对应的销售品信息！");
                        }
                        if (offerInfoList.size() > 1) {
                            if (paymentModeCd == null || "".equals(paymentModeCd.trim())) {
                                throw new Exception("产品编码对应的付费模式不存在！");
                            } else {
                                throw new Exception("根据销售品" + offerNbr + "编码产品编码" + prodNbr + "找到多个销售品信息！");
                            }
                        }*/
                        Map offerInfoMap = new HashMap();
                        if(offerInfoList!=null&&offerInfoList.size()>0) {
                             offerInfoMap = (Map) offerInfoList.get(0);
                        }
                        String productId = StringUtil.obj2Str(offerInfoMap.get("PRODUCT_ID"));
                        String prodOfferId = StringUtil.obj2Str(offerInfoMap.get("PROD_OFFER_ID"));
                        //add by yinjj 增加判断，如果产品id为空，则重新赋值
                        if(StringUtil.isEmptyOrNull(productId)){
                            List<String> prodList = prodPreOrderMapperServcie.queryProductIdByNbr(prodNbr);
                            if(prodList != null && prodList.size()>0){
                                productId = StringUtil.obj2Str(prodList.get(0));
                            }
                        }
                        //add by yinjj 增加判断，如果销售品id为空，则重新赋值
                        if(StringUtil.isEmptyOrNull(prodOfferId)){
                            List<String> prodOfferList = prodPreOrderMapperServcie.queryProdOfferIdByNbr(offerNbr);
                            if(prodOfferList != null && prodOfferList.size()>0){
                                prodOfferId = StringUtil.obj2Str(prodOfferList.get(0));
                            }
                        }
                        if(StringUtil.isNotEmptyOrNull(productId)) {
                            List<String> accNbrTypeCdList = prodPreOrderMapperServcie.queryAccNbrTypeCd(productId);
                            if (accNbrTypeCdList != null && accNbrTypeCdList.size() != 0) {
                                accNbrTypeCd = StringUtil.obj2Str(accNbrTypeCdList.get(0));
                            }
                        }
                        ProdPreOrder prodPreOrder = new ProdPreOrder();
                        prodPreOrder.setNotificationId(new BigDecimal(notificationId));
                        prodPreOrder.setCustOrderId(new BigDecimal(custOrderId));
                        prodPreOrder.setAcceptDate(acceptDate);
                        prodPreOrder.setAcceptRegionId(acceptRegionId);
                        prodPreOrder.setOperType(operType);
                        prodPreOrder.setAcceptSystemUserCode("");
                        prodPreOrder.setAccNbr(accNbr);
                        prodPreOrder.setAccNbrTypeCd(accNbrTypeCd);
                        prodPreOrder.setStatusCd(notifyStatusCd);
                        prodPreOrder.setCreateStaff(createStaff);
                        prodPreOrder.setSysSource(sysSource);
                        prodPreOrder.setExtCustOrderId(extCustOrderId);
                        if (custId != null && !"".equals(custId.trim())) {
                            prodPreOrder.setCustId(Long.getLong(custId));
                        }
                        if(StringUtil.isNotEmptyOrNull(prodOfferId)) {
                            prodPreOrder.setProdOfferId(Integer.parseInt(prodOfferId));
                        }
                        if(StringUtil.isNotEmptyOrNull(productId)) {
                            prodPreOrder.setProductId(Integer.parseInt(productId));
                        }
                        prodPreOrder.setRemark(remark);
                        prodPreOrder.setInParam(inParamBodys);
                        prodPreOrderMapper.insert(prodPreOrder);

                        ProdPreOrderHis prodPreOrderHis = new ProdPreOrderHis();
                        PropertyUtils.copyProperties(prodPreOrderHis, prodPreOrder);
                        prodPreOrderHis.setHisAccept(new BigDecimal(notificationId));
                        prodPreOrderHis.setHisDate(Long.parseLong(dateString));
                        prodPreOrderHis.setHisLogin("0");
                        prodPreOrderHis.setHisTime(currentDate);
                        prodPreOrderHis.setHisType("I");
                        prodPreOrderHisMapper.insert(prodPreOrderHis);
                    }
                }
            } else {
                //更新正表状态
                ProdPreOrder prodPreOrder = new ProdPreOrder();
                prodPreOrder.setStatusCd(notifyStatusCd);
                prodPreOrder.setRemark(reasonDesc);
                ProdPreOrderExample prodPreOrderExample = new ProdPreOrderExample();
                ProdPreOrderExample.Criteria criteria = prodPreOrderExample.createCriteria();
                criteria.andCustOrderIdEqualTo(new BigDecimal(custOrderId));
                criteria.andExtCustOrderIdEqualTo(extCustOrderId);
                prodPreOrderMapper.updateByExampleSelective(prodPreOrder, prodPreOrderExample);
                //更新历史表内的记录
                List<ProdPreOrder> prodPreOrderList = prodPreOrderMapper.selectByExampleWithBLOBs(prodPreOrderExample);
                for (int i = 0; i < prodPreOrderList.size(); i++) {
                    ProdPreOrderHis prodPreOrderHis = new ProdPreOrderHis();
                    PropertyUtils.copyProperties(prodPreOrderHis, prodPreOrderList.get(i));
                    prodPreOrderHis.setHisAccept(new BigDecimal(notificationId));
                    prodPreOrderHis.setHisDate(Long.parseLong(dateString));
                    prodPreOrderHis.setHisLogin("2");
                    prodPreOrderHis.setHisTime(currentDate);
                    prodPreOrderHis.setHisType("U");
                    prodPreOrderHisMapper.insert(prodPreOrderHis);
                }

            }
            log.info("#######################结束服务doOrderNotificationJson");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
            throw new Exception(e.getMessage());
        }
        return inMap;
    }

    public static String toString(Object target) {
        String value = "";
        if (target != null) {
            value = String.valueOf(target);
        }
        return value;

    }
}
